﻿using System;
using System.Collections.Concurrent;

using zijian666.Core.Abstractions;

namespace zijian666.Converts.Core;

/// <summary>
/// 字符串序列化工具集合
/// </summary>
public class StringSerializerCollection
{
    /// <summary>
    /// 根据序列化协议名称储存序列化工具
    /// </summary>
    private readonly ConcurrentDictionary<string, IStringSerializer> _items
        = new(StringComparer.OrdinalIgnoreCase);

    /// <summary>
    /// 设置或获取默认序列化协议
    /// </summary>
    public static string DefaultProtocol { get; set; } = "json";
    /// <summary>
    /// 注册序列化工具
    /// </summary>
    public void Register(IStringSerializer serializer) => _items[serializer.Protocol] = serializer;

    /// <summary>
    /// 根据序列化协议获取序列化工具
    /// </summary>
    public IStringSerializer? this[string protocol]
        => _items.TryGetValue(protocol, out var value) ? value : null;

    /// <summary>
    /// 检查指定序列化工具是否存在
    /// </summary>
    public bool IsExists(string protocol) => _items.ContainsKey(protocol);

    /// <summary>
    /// 获取默认的序列化工具
    /// </summary>
    public IStringSerializer? Default => this[DefaultProtocol];
}
